local Parser = class("Parser")

function Parser:ctor()

end

Parser.parse = function(protos)
    local maps = {}
    for(local key in protos) do
        maps[key] = parseObject(protos[key])
    end
    return maps
end

function parseObject(obj) 
    local proto = {}
    local nestProtos = {}
    local tags = {}

    for(local name in obj) do
        local tag = obj[name]
        local params = name.split(' ')

        switch(params[0]) 
            case 'message':
                if(params.length ~= 2)
                    continue
                nestProtos[params[1]] = parseObject(tag)
                continue
            case 'required':
            case 'optional':
            case 'repeated': 
                --params length should be 3 and tag can't be duplicated
                if(params.length ~= 3 or tags[tag])
                    continue
                
                proto[params[2]] = 
                    option : params[0],
                    type : params[1],
                    tag : tag
                
                tags[tag] = params[2]
            end
        end
	end	

    proto.__messages = nestProtos
    proto.__tags = tags
    return proto
end

return Parser

--(function (exports) 
--
--    exports.Protobuf.Parser = 
--    local Parser = exports.Protobuf.Parser
--
--    Parser.parse = function(protos)
--        local maps = 
--        for(local key in protos)
--            maps[key] = parseObject(protos[key])
--        
--
--        return maps
--    
--
--    function parseObject(obj) 
--        local proto = 
--        local nestProtos = 
--        local tags = 
--
--        for(local name in obj) 
--            local tag = obj[name]
--            local params = name.split(' ')
--
--            switch(params[0]) 
--                case 'message':
--                    if(params.length ~= 2)
--                        continue
--                    nestProtos[params[1]] = parseObject(tag)
--                    continue
--                case 'required':
--                case 'optional':
--                case 'repeated': 
--                    --params length should be 3 and tag can't be duplicated
--                    if(params.length ~= 3 or tags[tag])
--                        continue
--                    
--                    proto[params[2]] = 
--                        option : params[0],
--                        type : params[1],
--                        tag : tag
--                    
--                    tags[tag] = params[2]
--                
--            
--        
--
--        proto.__messages = nestProtos
--        proto.__tags = tags
--        return proto
--    
--
--)(HY.net)
